package cn.hg.solon.youcan.system.provider;

import java.util.List;
import java.util.Map;

import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.bean.copier.CopyOptions;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.text.CharSequenceUtil;
import org.dromara.hutool.core.text.StrValidator;
import org.dromara.hutool.core.util.ObjUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;

import com.easy.query.api4j.client.EasyQuery;
import com.easy.query.api4j.select.Queryable;
import com.easy.query.solon.annotation.Db;

import cn.hg.solon.youcan.common.constant.AppConstants;
import cn.hg.solon.youcan.common.constant.WebConstants;
import cn.hg.solon.youcan.common.enums.BeanStatus;
import cn.hg.solon.youcan.common.enums.DataScope;
import cn.hg.solon.youcan.common.exception.ServiceException;
import cn.hg.solon.youcan.system.entity.Dept;
import cn.hg.solon.youcan.system.entity.EqDept;
import cn.hg.solon.youcan.system.entity.EqRole;
import cn.hg.solon.youcan.system.entity.EqRoleDeptMapping;
import cn.hg.solon.youcan.system.entity.EqUser;
import cn.hg.solon.youcan.system.entity.Role;
import cn.hg.solon.youcan.system.service.DeptService;

/**
 * @author 胡高
 */
@Component
public class EqDeptProvider implements DeptService {

    @Db("db1")
    private EasyQuery easyQuery;

    private Queryable<EqDept> buildQuery(Map<String, Object> paraMap) {
        String word = (String)paraMap.get("word");
        String sortField = (String)paraMap.get("sortField");
        String sortType = (String)paraMap.get("sortType");

        boolean customOrder = StrValidator.isNotBlank(sortField) && StrValidator.isNotBlank(sortType);

        // GROUP_CONCAT子查询
        Queryable<String> groupConcatQuery =
            // FROM sys_dept AS t1
            this.easyQuery.queryable(EqDept.class)
            // WHERE (t1.`name` LIKE '%${word}$' OR t1.`leader` LIKE '%${word}$' OR t1.`phone` LIKE '%${word}$'
            //      OR t1.`email` LIKE '%${word}$')
            .where(w -> w.and(StrValidator.isNotBlank(word),
                a -> a.like(EqDept::getName, word)
                .or().like(EqDept::getLeader, word)
                .or().like(EqDept::getPhone, word)
                .or().like(EqDept::getEmail, word)))
            // SELETE GROUP_CONCAT(t2.`ancestors`)
            .select(String.class, o -> o.sqlNativeSegment("GROUP_CONCAT({0})", c -> c.expression(EqDept::getAncestors)));

        // FROM sys_dept AS t
        return this.easyQuery.queryable(EqDept.class)
            // WHERE (t.`name` LIKE '%${word}$' OR t.`leader` LIKE '%${word}$' OR t.`phone` LIKE '%${word}$'
            //      OR t.`email` LIKE '%${word}$'
            .where(w -> w.and(StrValidator.isNotBlank(word),
                a -> a.like(EqDept::getName, word)
                .or().like(EqDept::getLeader, word)
                .or().like(EqDept::getPhone, word)
                .or().like(EqDept::getEmail, word)
                // OR FIND_IN_SET(t.`id`, (${GROUP_CONCAT子查询})))
                .or().sqlNativeSegment("FIND_IN_SET({0}, ({1}))",
                    c -> c.expression(EqDept::getId).expression(groupConcatQuery))
                ))
            // 排序字段
            .orderBy(customOrder, ob -> ob.sqlNativeSegment(CharSequenceUtil.toUnderlineCase(sortField)),
                !CharSequenceUtil.equalsIgnoreCase(sortType, WebConstants.ORDER_DIRECTION_DESC));
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DeptService#checkUnique(cn.hg.solon.youcan.system.entity.Dept)
     */
    @Override
    public boolean checkUnique(Dept bean) {
        return !this.easyQuery
            // FROM sys_dept AS t
            .queryable(EqDept.class)
            // WHERE t.`parent_id` = ${bean.parentId}
            .where(w -> w.eq(EqDept::getParentId, bean.getParentId())
                // t.`name` = ${bean.name}
                .eq(EqDept::getName, bean.getName())
                // t.`id` <> ${bean.id}
                .ne(ObjUtil.isNotNull(bean.getId()), EqDept::getId, bean.getId()))
            .any();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DeptService#delete(java.lang.Integer)
     */
    @Tran
    @Override
    public boolean delete(Integer id) {
        /*
         * 检查是否子项
         */
        if (this.easyQuery.queryable(EqDept.class).where(w -> w.eq(EqDept::getParentId, id)).any()) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "存在子项，不允许删除！");
        }

        /*
         * 检查是否已分配于角色
         */
        if (// FROM sys_dept AS t
            this.easyQuery.queryable(EqDept.class)
            // LEFT JOIN sys_role_dept_mapping AS t2 ON t1.`dept_id` = t.`id`
            .leftJoin(EqRoleDeptMapping.class, (d, rd) -> rd.eq(d, EqRoleDeptMapping::getDeptId, EqDept::getId))
            // LEFT JOIN sys_role AS t3 ON t3.`id` = t2.`role_id`
            .leftJoin(EqRole.class, (d, rd, r) -> r.eq(rd, EqRole::getId, EqRoleDeptMapping::getRoleId))
            // WHERE t2.`dept_id` = ${id} AND t3.`data_scope` = 'CUSTOM'
            .where((d, rd,r) -> rd.eq(EqRoleDeptMapping::getDeptId, id).then(r.eq(EqRole::getDataScope, DataScope.CUSTOM.name())))
            .any()) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "已分配于角色，不允许删除！");
        }

        /*
         * 检查部门下是否存在用户
         */
        if (// FROM sys_user AS t
            this.easyQuery.queryable(EqUser.class)
            // WHERE t.`dept_id` = ${id}
            .where(w -> w.eq(EqUser::getDeptId, id))
            .any()) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "部门下存在用户，不允许删除！");
        }

        return this.easyQuery.deletable(EqDept.class).whereById(id).executeRows() > 0;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DeptService#get(java.lang.Integer)
     */
    @Override
    public Dept get(Integer id) {
        return this.easyQuery.queryable(EqDept.class).where(w -> w.eq(EqDept::getId, id)).firstOrNull();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DeptService#insert(cn.hg.solon.youcan.system.entity.Dept)
     */
    @Tran
    @Override
    public boolean insert(Dept bean) {
        /*
         * 无父对象ID时，默认为0
         */
        if (ObjUtil.isNull(bean.getParentId())) {
            bean.setParentId(0);
        }

        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "部门名称已经存在，请更换其它值！");
        }

        Dept partner = this.get(bean.getParentId());
        bean.setAncestors(ObjUtil.isNull(partner) ? "0" : partner.getAncestors() + "," + bean.getParentId());

        EqDept cloneBean = BeanUtil.copyProperties(bean, EqDept.class);

        return this.easyQuery.insertable(cloneBean).executeRows() > 0;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DeptService#listBy(java.util.Map)
     */
    @Override
    public List<? extends Dept> listBy(Map<String, Object> paraMap) {
        return this.buildQuery(paraMap).toList();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DeptService#listByRole(cn.hg.solon.youcan.system.entity.Role)
     */
    @Override
    public List<? extends Dept> listByRole(Role role) {
        if (ObjUtil.isNull(role)) {
            return ListUtil.empty();
        }

        // FROM sys_dept AS t
        return this.easyQuery.queryable(EqDept.class).distinct()
            // LEFT JOIN sys_role_dept_mapping AS t1 ON t1.`dept_id` = t.`id`
            .leftJoin(EqRoleDeptMapping.class, (d, rd) -> rd.eq(d, EqRoleDeptMapping::getDeptId, EqDept::getId))
            // WHERE t.`status` = 'ON' AND t1.`role_id` = ${role.id}
            .where((d, rd) -> d.eq(EqDept::getStatus, BeanStatus.ON.name())
                .then(rd.eq(EqRoleDeptMapping::getRoleId, role.getId())))
            .orderBy(ob -> ob.column(EqDept::getSort), true)
            .toList();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DeptService#listByStatus(java.lang.String)
     */
    @Override
    public List<? extends Dept> listByStatus(String status) {
        // FROM sys_dept AS t
        return this.easyQuery.queryable(EqDept.class)
            // WHERE t.`status` = ${status}
            .where(w -> w.eq(StrValidator.isNotBlank(status), EqDept::getStatus, status))
            // ORDER BY t.`sort` ASC
            .orderBy(ob -> ob.column(EqDept::getSort), true)
            .toList();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DeptService#update(cn.hg.solon.youcan.system.entity.Dept)
     */
    @Tran
    @Override
    public boolean update(Dept bean) {
        /*
         * 无父对象ID时，默认为0
         */
        if (ObjUtil.isNull(bean.getParentId())) {
            bean.setParentId(0);
        }

        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "部门名称已经存在，请更换其它值！");
        }

        Dept partner = this.get(bean.getParentId());
        bean.setAncestors(ObjUtil.isNull(partner) ? "0" : partner.getAncestors() + "," + bean.getParentId());

        EqDept cloneBean = (EqDept)this.get(bean.getId());

        BeanUtil.copyProperties(bean, cloneBean, CopyOptions.of().setIgnoreNullValue(true));

        return this.easyQuery.updatable(cloneBean).executeRows() > 0;

    }

}
